package com.ternnetwork.oa.service.impl.job;

import com.ternnetwork.commons.utils.DateUtils;
import com.ternnetwork.oa.enums.work.EventRemindTime;
import com.ternnetwork.oa.job.EventRemindJob;
import com.ternnetwork.oa.service.job.EventJobService;
import com.ternnetwork.oa.utils.EventRemindTimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.Date;


@Service
@Slf4j
public class EventJobServiceImpl implements EventJobService {

    @Autowired
    @Qualifier(value = "scheduler")
    private Scheduler scheduler;

    public void createJob(Long eventId, Date start, EventRemindTime remindTime) throws SchedulerException {

        if (!EventRemindTime.NEVER.equals(remindTime)) {

            String jobName = "event_remind_" + eventId;

            String jobGroup = "event_remind";

            JobDetail jobDetail = JobBuilder.newJob(EventRemindJob.class).withIdentity(jobName, jobGroup).build();

            String triggerTimeCronExpression = getTriggerTimeCronExpression(start, remindTime);
            //表达式调度构建器(即任务执行的时间,不立即执行)
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(triggerTimeCronExpression).withMisfireHandlingInstructionDoNothing();

            //按新的cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobName, jobGroup).startAt(new Date()).withSchedule(scheduleBuilder).build();
            //put some parameters for job
            trigger.getJobDataMap().put("eventId", eventId);

            scheduler.scheduleJob(jobDetail, trigger);
        }
    }

    private String getTriggerTimeCronExpression(Date start, EventRemindTime remindTime) {
        Date triggerTime = EventRemindTimeUtils.convertRemindTime(start, remindTime);
        String dateFormat = "ss mm HH dd MM ? yyyy";
        return DateUtils.format(triggerTime, dateFormat);
    }



    public void deleteJob(Long eventId) throws SchedulerException {
        String jobName = "event_remind_" + eventId;
        String jobGroup = "event_remind";
        JobKey jobKey = new JobKey(jobName, jobGroup);
        if (scheduler.checkExists(jobKey)) {
            scheduler.deleteJob(jobKey);
        }
    }

    public void updateJob(Long eventId, Date start, EventRemindTime remindTime) throws SchedulerException{
        deleteJob(eventId);
        createJob(eventId,start,remindTime);
    }
}
